<?php

namespace Api\Event;
//use Com\QQ\XingeApp;

use Api\Event\CacheEvent;
use Common\Dto\PushDto;

/**
 * 推送信息
 * @author Legend. <xcx_legender@qq.com>
 * @param
 * @return
 */
require_once THINK_PATH . "Library/Com/QQ/XingeApp.class.php";
class PushEvent extends BaseEvent {
	const PUSH_TYPE_MAIL = 'notice';
	const PUSH_TYPE_AT = 'notice';
	const PUSH_TYPE_MATCH = 'notice';
	const PUSH_TYPE_VIDEO = 'notice';
	const PUSH_TYPE_ACTIVE = 'notice';
	const PUSH_TYPE_VIDEO_ZAN = 'notice';
	const PUSH_TYPE_VIDEO_COMMENT = 'notice';
	const PUSH_TYPE_LIKE = 'notice';
	const PUSH_TYPE_FANS = 'notice';
	const PUSH_TYPE_NOTICE = 'notice';  //公告

	const PUSH_TYPE_MESSAGE = 'message';

	const ANDROID_PACK_PREFIX = 'com.tv66.tv.ac.';

	/**
	 * 推送给@的某(些)人
	 * @author Legend. <xcx_legender@qq.com>
	 * @param string $nickname 发送者的昵称;  mix $to; 接受者的账号 (180..) 或者账号数组  array('180..', '186..')
	 * @return bool true or false;
	 */

	public function at(&$senderUser, $to, $toUids, &$video) {
		$nickname = $senderUser['nickname'];
		$custom = [
			'content' => "{$nickname}在评论中@了你",
			'type' => 'at',
			'activity' => 'AtMeActivity',
			'event_id' => $video['id'],
		];
		if (!$nickname || !$to) {
			return false;
		}
		$to_array = [
			'uid' => $toUids,
			'nickname' => $to,
		];
		$res = $this->doQueue(self::PUSH_TYPE_AT, $nickname, $to_array, $custom);
		$this->pushToTool($senderUser, $toUids, $custom);
		return $res;
		#deprecated  使用队列进行发送 以下内容弃用
		// $res = \XingeApp::PushAccountAndroid(C('PUSH_ANDROID.ACCESS_ID'), C('PUSH_ANDROID.SECRET_KEY'), "你收到一条消息", "{$nickname}在评论中@了你", $to);
		// var_dump($res);
		// $push = new \XingeApp(C('PUSH_ANDROID.ACCESS_ID'), C('PUSH_ANDROID.SECRET_KEY'));
		// $mess = new \Message();
		// $mess->setTitle('你收到一条消息');
		// $mess->setContent("{$nickname}在评论中@了你");
		// $mess->setType(\Message::TYPE_NOTIFICATION);
		// $mess->setStyle(new \Style(0, 1, 1));
		// $action = new \ClickAction();
		// $action->setActionType(\ClickAction::TYPE_ACTIVITY);
		// $action->setActivity('com.tv66.tv.ac.AtMeActivity');
		// $mess->setAction($action);
		// $ret = is_array($to) ? $push->PushAccountList(0, $to, $mess) : $push->PushSingleAccount(0, $to, $mess);
		// // var_dump($ret);
		// return $ret;
		// return $ret['ret_code'] == 0;
	}

	// 发私信给某人
	public function mail(&$senderUser, &$toUser, $msg) {
		$nickname = $senderUser['nickname'];
		$to = $toUser['nickname'];
		$custom = [
			'content' => "{$nickname}对你说:{$msg}",
			'type' => 'sixin',
			'activity' => 'MyMessageConversationActivity',
		];
		if (!$nickname || !$to) {
			return false;
		}
		$res = $this->doQueue(self::PUSH_TYPE_MAIL, $nickname, $toUser, $custom);
		
		$this->pushToTool($senderUser, $toUser['uid'], $custom);
		return $res;
	}

	public function match($id, $msg, $game_id) {
		$custom = [
			'event_id' => $id,
			'type' => 'event',
			'activity' => 'MatchDetailActivity',
			'content' => $msg,
		];

		$tags = [
			'game:'.$game_id,
		];
		$res = $this->doQueue(self::PUSH_TYPE_MATCH, '', '', $custom, $tags);
		return $res;
	}

	public function video($id, $msg, $game_id) {
		$custom = [
			'event_id' => $id,
			'type' => 'video',
			'activity' => 'VedioInfo2Activity',
			'content' => $msg,
		];

		$tags = [
			'game:'.$game_id,
		];
		$res = $this->doQueue(self::PUSH_TYPE_VIDEO, '', '', $custom, $tags);
		return $res;
	}

	public function active($msg, $uri, $game_id) {
		$custom = [
			'uri' => $uri,
			'content' => $msg,
			'type' => 'active',
			'activity' => 'WebViewActivty',
		];
		$tags = [
			'game:'.$game_id,
		];
		$res = $this->doQueue(self::PUSH_TYPE_ACTIVE, '', '', $custom, $tags);
		return $res;
	}

	/**
	 * 推送公告
	 * @author liubo <liubo@ilongyuan.com.cn>
	 * @param  String $msg 内容
	 */
	public function notice($id, $msg, $plat)
	{
		$custom = [
			'news_id'   => $id,
			'content'   => $msg,
			'type'      => 'notice',
			'activity'  => 'InformationDetailActivity',
		];
		$res = $this->doQueue(self::PUSH_TYPE_NOTICE, '', '', $custom, '', $plat, true);
		return $res;
	}

	public function videoComment(&$senderUser, &$toUser, &$video, $msg) {
		$nickname = $senderUser['nickname'];
		$to = $toUser['nickname'];
		$id = $video['id'];
		$content = "[系统消息]{$nickname}评论了你的视频:{$msg}";
		$custom = [
			'event_id' => $id,
			'content' => $content,
			'type' => 'video_comment',
			'activity' => 'MyMessageActivity',
		];
		if (!$nickname || !$to || !$id) {
			return false;
		}
		$res = $this->doQueue(self::PUSH_TYPE_VIDEO_COMMENT, $nickname, $toUser, $custom);
		event('UserNotice')->addComment($senderUser, $toUser['uid'], $video, $content);
		$this->pushToTool($senderUser, $toUser['uid'], $custom);
		// 给用户添加一条通知消息记录
		// event('UserNotice')->addVideoComment($senderUser, $toUser['uid'], $video, $content);
		return $res;
	}

	public function videoZan(&$senderUser, &$toUser, &$video) {
		$nickname = $senderUser['nickname'];
		$to = $toUser['nickname'];
		$id = $video['id'];
		$content = "[系统消息]{$nickname}赞了你的视频";
		$custom = [
			'event_id' => $id,
			'content' => $content,
			'type' => 'video_zan',
			'activity' => 'MyMessageActivity',
		];
		if (!$nickname || !$to || !$id) {
			return false;
		}
		$res = $this->doQueue(self::PUSH_TYPE_VIDEO_ZAN, $nickname, $toUser, $custom);
		event('UserNotice')->addVideoZan($senderUser, $toUser['uid'], $video, $content);
		$this->pushToTool($senderUser, $toUser['uid'], $custom);
		return $res;
	}


	public function like(&$senderUser, &$toUser) {
		$nickname = $senderUser['nickname'];
		$to = $toUser['nickname'];
		if (!$nickname || !$to) {
			return false;
		}
		$content = "[系统消息]{$nickname}送了你一颗心";
		$custom = [
			'content' => $content,
			'type' => 'like',
			'activity' => 'MyMessageActivity',
		];
		$res = $this->doQueue(self::PUSH_TYPE_LIKE, $nickname, $toUser, $custom);
		// 给用户添加一条通知消息记录
		event('UserNotice')->addLike($senderUser, $toUser['uid'], $content);
		$this->pushToTool($senderUser, $toUser['uid'], $custom);
		return $res;
	}

	public function fans(&$senderUser, &$toUser) {
		$nickname = $senderUser['nickname'];
		$to = $toUser['nickname'];
		if (!$nickname || !$to) {
			return false;
		}
		$content = "[系统消息]{$nickname}关注了你";
		$custom = [
			'content' => $content,
			'type' => 'fans',
			'activity' => 'MyMessageActivity', #TODO 安卓的activity
		];
		$res = $this->doQueue(self::PUSH_TYPE_FANS, $nickname, $toUser, $custom);
		event('UserNotice')->addFans($senderUser, $toUser['uid'], $content);
		$this->pushToTool($senderUser, $toUser['uid'], $custom);
		return $res;
	}

	/**
	 * 打赏推送
	 * @author liubo <liubo@ilongyuan.com.cn>
	 * @param  array  $sender 打赏者
	 * @param  array  $to     被打赏者
	 * @param  string  $type   类型 video/comment
	 * @param  integer $money  金额
	 * @param  array   $object
	 * @param  boolean $global 是否全局推送
	 */
	public function reward($sender, $to, $type, $money, $object, $global = false)
	{
		switch ($type) {
			case 'video':
				$typestr = '视频';
				$object_id = $object['id'];
				break;
			case 'comment':
				$typestr = '评论';
				$object_id = $object['video_id'];
				break;
		}
		$content = "[系统消息]{$sender['nickname']}对你";
		$typestr && $content .= "的{$typestr}";
		$content .= "打赏了{$money}个⑥币";
		$custom = [
			'content' => $content,
			'type' => "reward_{$type}",
			'video_id' => $object_id,
			'activity' => 'VedioInfo2Activity',
		];
		$res = $this->doQueue(self::PUSH_TYPE_NOTICE, $sender['nickname'], $to, $custom);
		$senderUser = [
			'uid' => $sender['id'],
			'nickname' => $sender['nickname'],
		];
		event('UserNotice')->addReward($senderUser, $to['uid'], $content);
		$this->pushToTool($senderUser, $to['uid'], $custom);

		if($global) {
			$content = "{$sender['nickname']}对{$to['nickname']}";
			$typestr && $content .= "的{$typestr}";
			$content .= "打赏了{$money}个⑥币";

			$custom = [
	            'content' => $content,
	            'type'  => 'global_reward_message',
	        ];
			$this->doQueue(self::PUSH_TYPE_MESSAGE, $sender['nickname'], '', $custom, '', '', true);
		}
		return $res;
	}

	// 加入队列
	protected function doQueue($message_type, $sender_name, $accounts, $custom, $tags = '', $plat = '', $toall = false) {
		/*is_array($accounts) && $accounts = implode(',', $accounts);
		$custom = json_encode($custom);
		$param = compact('message_type', 'sender_name', 'accounts', 'custom');
		$api = C('QUEUE_DOMAIN') . '/message/xinge_msg_push';
		if (I('debug')) {
			// echo $api;
			// print_r($param);
			I('ios') && $param['environment'] = I('ios');
		}

		// 发送给android
		$param['environment'] = 0;
		$res = http_request($api, $param, false, 'POST');

		// 发送给IOS
		$param['environment'] = 1;
		$res = http_request($api, $param, false, 'POST');

		return $res;*/


		$custom['nick'] = $sender_name;
		!empty($custom['activity']) && $custom['activity'] = self::ANDROID_PACK_PREFIX.$custom['activity'];
		#切换成PHP版本 tcp async
		// $data = ['action' => 'push', 'data' => [
  //           // 'test'      => 1,
  //           'plat'      => $plat,
  //           'toall'     => (empty($accounts) && empty($tags)) ? 1 : 0,
  //           'type'      => $custom['type'],
  //           'accounts'  => is_array($accounts) ? $accounts : [$accounts],
  //           'custom'    => $custom,
  //           'tags'      => $tags,
  //           'messageType' => $message_type,
  //       ]];
  //       local_tcp_request(6060, $data);

		$Dto = new PushDto;
        $Dto->content  = $custom['content'];
        $Dto->activity = $custom['activity'];
        $Dto->type     = $custom['type'];
        $Dto->custom   = $custom;

        if (!empty($accounts)) {
        	!empty($accounts['uid']) && $Dto->accounts_ids = is_array($accounts['uid']) ? $accounts['uid'] : [$accounts['uid']];
        	!empty($accounts['nickname']) && $Dto->accounts = is_array($accounts['nickname']) ? $accounts['nickname'] : [$accounts['nickname']];
        }
        // !empty($accounts) && $Dto->accounts = is_array($accounts) ? $accounts : [$accounts];
        !empty($tags) && $Dto->tags = $tags;
        !empty($plat) && $Dto->plats = is_array($plat) ? $plat : [$plat];
        $Dto->toAll = $toall;
        $Dto->title = '66Play';
        $Dto->messageType = ($message_type == 'message') ? PushDto::MESS_MESSAGE : PushDto::MESS_NOTICE;

        $param = ['data' => json_encode($Dto)];
        event('LocalClient')->doRequest('push', $param);
	}

	protected function pushToAndroid($title, $content, $activity)
	{
		$push = new \XingeApp(C('PUSH_ANDROID.ACCESS_ID'), C('PUSH_ANDROID.SECRET_KEY'));
		$mess = new \Message();
		$mess->setTitle($title);
		$mess->setContent($content);
		$mess->setType(\Message::TYPE_NOTIFICATION);
		$mess->setStyle(new \Style(0, 1, 1));
		$action = new \ClickAction();
		$action->setActionType(\ClickAction::TYPE_ACTIVITY);
		$action->setActivity($activity);
		$mess->setAction($action);
		$ret = is_array($to) ? $push->PushAccountList(0, $to, $mess) : $push->PushSingleAccount(0, $to, $mess);
	}

	protected function pushToIOS()
	{
		
	}

	protected function pushToTool(&$senderUser, $account_ids, $custom) {
		$sender_name = $senderUser['nickname'];
		$account_ids = !is_array($account_ids) ? explode(',', $account_ids) : $account_ids;
		// 发送给工具 如果有接受者  全部发送不接收
		// #TODO 使用redis记录数据
		$data = json_encode(array_merge($custom, ['sender_name' => $sender_name, 'sender_id' => $senderUser['uid']]));
		$cache = CacheEvent::instance(4);
		foreach ($account_ids as $uid) {
			// \Think\Log::record("[DEBUG -- PUSH TOOL --]: UID {$uid}");
			$key = "IMBA.PUSH.TOOL.UID.{$uid}";
			$cache->rPush($key, $data);
		}
	}

}